package com.ruoyi.system.controller;

import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.parm.CancelParm;
import com.ruoyi.system.domain.parm.SysOrderParm;
import com.ruoyi.system.exception.GlobalSysException;
import com.ruoyi.system.service.*;
import com.ruoyi.system.util.KeyUtil;
import com.ruoyi.system.util.MathExtend;
import com.ruoyi.system.util.MathForLong;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.UUID;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2024-04-02
 */
@Api(tags = "用户订单管理")
@RestController
@RequestMapping("/mem/order")
public class MemOrderController extends BaseController
{
    @Autowired
    private ISysOrderService sysOrderService;
    @Autowired
    private ISysBusinessService sysBusinessService;
    @Autowired
    private ISysParkingSpacesService sysParkingSpacesService;
    @Autowired
    private ISysMemberService sysMemberService;

    @Autowired
    private ISysPreferentialService sysPreferentialService;
    @Autowired
    private ISysCancelOrderFeeService sysCancelOrderFeeService;

    @Autowired
    private ISysParkingService sysParkingService;

    /**
     * 查询【请填写功能名称】列表
     */
    @ApiOperation(value = "用户订单list")
    @GetMapping("/list")
    public TableDataInfo list(SysOrder sysOrder) throws Exception {
        SysMember user = sysMemberService.getUserInfo();
        if(null == user){
            throw new Exception("用户未登陆");
        }
        sysOrder.setMemberId(user.getId() );
        startPage();
        List<SysOrder> list = sysOrderService.selectSysOrderList(sysOrder);
        return getDataTable(list);
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @ApiOperation(value = "用户订单详情")
    @GetMapping(value = "/info")
    public AjaxResult getInfo(@RequestParam(name = "id",required = true) String id) throws Exception {

        SysMember user = sysMemberService.getUserInfo();
        if(null == user){
            throw new Exception("用户未登陆");
        }

        return success(sysOrderService.selectSysOrderById(id));
    }

    /**
     * 用户创建订单【请填写功能名称】
     */
    @ApiOperation(value = "创建订单")
    @PostMapping("add")
    public AjaxResult add(@RequestBody @Valid SysOrderParm sysOrder) throws Exception {

        SysMember user = sysMemberService.getUserInfo();
        if(null == user){
            throw new Exception("用户未登陆");
        }

        String parkingSpacesId = sysOrder.getParkingSpacesId();
        SysParkingSpaces parkingSpaces = sysParkingSpacesService.selectSysParkingSpacesById(parkingSpacesId);
       if(null==parkingSpaces){

           throw new GlobalSysException("停车位不存在");
       }
        if(!parkingSpaces.getParkingId().equals(sysOrder.getParkingId())){
            throw new GlobalSysException("停车场错误");
        }
        if(parkingSpaces.getStatus()!=0){
            throw new GlobalSysException("停车位已经占用或已经关闭");
        }
        // 查询停车场是否关闭
       Integer parkingStatus = sysParkingService.selectSysParkingStatusById(sysOrder.getParkingId() );
        if(parkingStatus==null){
            throw new GlobalSysException("停车场无效");
        }
        if(parkingStatus!=1){
            throw new GlobalSysException("停车场已经关闭或已停用");
        }
        SysOrder order=new SysOrder();
        Date date = new Date();
        order.setId(UUID.randomUUID().toString());
        order.setOrderNo(KeyUtil.generateUniqueKey());
        order.setMemberId(user.getId());
        order.setParkingId(parkingSpaces.getParkingId());
        order.setParkingSpacesId(parkingSpacesId);
        order.setBusinessId(parkingSpaces.getBusinessId());


        order.setCreateTime( date);
        order.setConsumptionStartTime( sysOrder.getConsumptionStartTime());
        order.setActualConsumptionEndTime( sysOrder.getConsumptionEndTime());

        long consumptionStartTime = sysOrder.getConsumptionStartTime().getTime() / 1000; // 获取秒级时间戳
        long consumptionEndTime = sysOrder.getConsumptionEndTime().getTime() / 1000; // 获取秒级时间戳

        if(consumptionStartTime >= consumptionEndTime){
            throw new GlobalSysException("预约时间设置错误");
        }
      //  long consumptionTime = consumptionEndTime - consumptionStartTime;
        long consumptionTime =  MathForLong.subtract(consumptionEndTime ,consumptionStartTime);
        if(consumptionTime <  3600 ){
            throw new GlobalSysException("预约时间设置不能小于一个钟");
        }
        long consumptionHour = MathForLong.divide(consumptionTime, 3600L);
        // 计算预约小时数
        order.setConsumptionHour(consumptionHour);

        // 查出商家设置的价格表
        List<SysPreferential> preferential = sysPreferentialService.selectSysPreferentialByParkingSpacesId(parkingSpacesId);
        if(preferential==null || preferential.size()==0){
            throw new GlobalSysException("商家未配置停车位价格");
        }
        BigDecimal consumptionAmount=null;
        for (SysPreferential  item : preferential){
            if(consumptionHour >=item.getGreaterThan()  && consumptionHour <=item.getLessThan() ){
                consumptionAmount=item.getPrice();
            }
        }

        if(consumptionAmount==null){
            throw new GlobalSysException("商家未配置停车位价格");

        }
        // 预约付款金额
        BigDecimal finalConsumptionAmount = consumptionAmount.multiply(BigDecimal.valueOf(consumptionHour)).setScale(2, BigDecimal.ROUND_UP);
        if(!String.valueOf(finalConsumptionAmount).equals(String.valueOf(sysOrder.getPreConsumptionAmount()) )){
            throw new GlobalSysException("价格计算有误！");
        }


        order.setPreConsumptionAmount(finalConsumptionAmount);
        order.setStatus(0);
        return toAjax(sysOrderService.insertSysOrder(order));
    }

    /**
     * 【取消订单支付手续费】
     */
    @ApiOperation(value = "取消订单支付手续费")
    @PostMapping(value = "/cancelPayFee")
    public AjaxResult cancelPayFee(@RequestBody @Valid CancelParm sysOrder) throws Exception {
        long nowTime = new Date().getTime() / 1000;  // 获取秒级时间戳
        SysMember user = sysMemberService.getUserInfo();
        if(null == user){
            throw new Exception("用户未登陆");
        }
        // 查询订单
        SysOrder ret = sysOrderService.selectSysOrderByIdOrderNo(sysOrder.getOrderNo());
        if(null == ret){
            throw new GlobalSysException("订单号无效");
        }
        if(!ret.getMemberId().equals(user.getId())){
            throw new GlobalSysException("订单号不存在");
        }
        if(ret.getStatus()==5 || ret.getStatus()==6){
            throw new GlobalSysException("订单已经取消,或订单已经支付取消费");
        }
        // 计算当前时间 和订单消费时间  的 时长
        long consumptionStartTime = ret.getConsumptionStartTime().getTime() / 1000;
        if(nowTime>=consumptionStartTime){
            throw new GlobalSysException("订单正在消费中，不能取消订单");
        }
        long cancelOrderTime = consumptionStartTime - nowTime;
        long cancelOrderHour = MathForLong.divideForRoudUp(cancelOrderTime, 3600L, 0);
        // 取消订单手续费
        List<SysCancelOrderFee> cancelOrder = sysCancelOrderFeeService.selectSysCancelOrderFeeByBusinessId(ret.getBusinessId());
        BigDecimal orderFee=new BigDecimal(0);
        if(cancelOrder.size()>0){
            for (SysCancelOrderFee item : cancelOrder){
                if(cancelOrderHour>= item.getAppointmentBefor() &&  cancelOrderHour>= item.getAppointmentAfter() ){
                    orderFee=item.getFee();
                }
            }
        }

        return success(String.valueOf(orderFee));
    }

    /**
     * 【用户取消订单】
     */
    @ApiOperation(value = "取消订单")
    @PostMapping(value = "/cancel")
    public AjaxResult cancelOrder(@RequestBody @Valid CancelParm sysOrder) throws Exception {
        long nowTime = new Date().getTime() / 1000;  // 获取秒级时间戳

        SysMember user = sysMemberService.getUserInfo();
        if(null == user){
            throw new Exception("用户未登陆");
        }
        // 查询订单
        SysOrder ret = sysOrderService.selectSysOrderByIdOrderNo(sysOrder.getOrderNo());
        if(null == ret){
            throw new GlobalSysException("订单号无效");
        }
        if(!ret.getMemberId().equals(user.getId())){
            throw new GlobalSysException("订单号不存在");
        }
        if(ret.getStatus()==5){
            throw new GlobalSysException("订单已经取消");
        }
        // 查询订单是否支付尾款（）
        if(ret.getStatus()!=6){
            throw new GlobalSysException("订单未支付取消订单手续费");
        }

        return toAjax(sysOrderService.cancelOrder(sysOrder));
    }


}
